package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理一些异常情况(购物车没有东西,地址簿没有为null)
        //判断购物车是否为null
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.selectDishOrSetmeal(shoppingCart);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //判断地址簿是否为null
        //根据地址id查询地址
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }


        //2.为订单表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);//Orders.PENDING
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orderMapper.insertOrders(orders);


        //3. 为订单详细表中插入多条数据
        List<OrderDetail> details = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());

            details.add(orderDetail);
        }
        orderDetailMapper.insertBatch(details); // 批量插入
        //4.清空购物车
        shoppingCartMapper.deleteByUserId(userId);
        //5.封装结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        // 开发环境下：直接调用支付成功的回调方法，模拟修改数据库数据为已支付
        // 生产环境应取消注释并使用实际的微信支付流程
        // 调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/

        /*if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        // 开发环境：模拟支付成功，直接调用paySuccess方法
        paySuccess(ordersPaymentDTO.getOrderNumber());

        // 构造一个空的OrderPaymentVO对象作为返回值（因为开发环境不需要真实的支付信息）
        return OrderPaymentVO.builder().build();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);


        //支付成功之后有来单提醒,用websocket向浏览器推送消息

        //约定传递过去3个参数 type orderId content
        Map map = new HashMap();
        map.put("type", 1);//1为来单提醒,2为催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + outTradeNo);

        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);//里面装的时json格式的数据

    }

    // 查询历史订单
    @Override
    public PageResult getPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 查询根据条件查询历史订单并强制转换
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        Page<Orders> page = orderMapper.selectOrderPage(ordersPageQueryDTO);

        // 集合这里需要自己查找
        List<OrderVO> list = new ArrayList<>();
        if (page != null && page.getTotal() > 0) {
            List<Orders> orders = page.getResult();
            for (Orders order : orders) {
                Long orderId = order.getId(); // 获取订单id
                // 根据订单id查找订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    //根据订单id查询订单详情
    @Override
    public OrderVO getOrderDetailByOrderId(Long OrderId) {

        //根据订单id和用户id查询订单
        Long userId = BaseContext.getCurrentId();
        Orders orders = orderMapper.selectOrderByOrderIdAndUserId(userId, OrderId);
        //根据订单id查询订单详情
        List<OrderDetail> list = orderDetailMapper.getOrderDetailByOrderId(OrderId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    //根据订单号修改订单状态,取消订单
    @Override
    public void cancelOrderById(Long id) {
        Long userId = BaseContext.getCurrentId();
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(id);
        orders.setUserId(userId);
        orderMapper.update(orders);
    }

    //客户催单
    @Override
    public void reminderOrder(Long id) {
        //首先根据订单id查询是否存在这个订单
        Orders orders = orderMapper.getById(id);//通过订单id查询订单,
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //调用websocket
        Map map = new HashMap();
        map.put("type", 2);//1:订单提醒 2:催单
        map.put("orderId", id);
        map.put("content", "订单号:" + orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /*再来一单*/
    @Override
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }


    //------以下是管理端的订单管理--------

    //订单管理
    @Override
    public PageResult getOrderPageAdmin(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //
        Page<Orders> page = orderMapper.selectOrderPage(ordersPageQueryDTO);

        // 集合这里需要自己查找
        List<OrderVO> list = new ArrayList<>();
        if (page != null && page.getTotal() > 0) {
            List<Orders> orders = page.getResult();
            for (Orders order : orders) {
                Long orderId = order.getId(); // 获取订单id
                // 根据订单id查找订单明细----注意这里只有name和number
                List<OrderDetail> orderDetails = orderDetailMapper.getOrderdetailNumberById(orderId);

                List<String> OrderDishesList = orderDetails.stream().map(detial -> detial.getName() + "*" + detial.getNumber()).collect(Collectors.toList());

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);

                orderVO.setOrderDishes(StringUtils.join(OrderDishesList, ";"));

                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);

    }

    @Override
    public OrderStatisticsVO getOrderStatusEver() {
        //2待接单toBeConfirmed 3已接单confirmed 4派送中deliveryInProgress
        Integer toBeConfirmedNumber = orderMapper.getCountStatusEver(Orders.TO_BE_CONFIRMED);
        Integer confirmedNumber = orderMapper.getCountStatusEver(Orders.CONFIRMED);
        Integer deliveryInProgressNumber = orderMapper.getCountStatusEver(Orders.DELIVERY_IN_PROGRESS);
        return OrderStatisticsVO
                .builder()
                .confirmed(confirmedNumber)
                .deliveryInProgress(deliveryInProgressNumber)
                .toBeConfirmed(toBeConfirmedNumber)
                .build();
    }


    @Override
    public OrderVO getOrderDetailByOrderIdAdmin(Long id) {

        Orders order = orderMapper.selectOrderByOrderIdAndUserId(null, id);

        // 订单详情的集合这里需要自己查找
        Long orderId = order.getId(); // 获取订单id
        // 根据订单id查找订单明细
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(orderId);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    //接单
    @Override
    public void receptOrderById(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO,orders);
        orderMapper.update(orders);
    }

    //拒单
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO ) {

        //退款做不了,涉及支付

        /*// 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        BeanUtils.copyProperties(ordersRejectionDTO,orders);
        orderMapper.update(orders);
    }

    //取消订单
    @Override
    public void cancelOrderByIdAdmin(OrdersCancelDTO ordersCancelDTO) {

        //退款写不了
        /*// 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/


        Orders orders = new Orders();
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        BeanUtils.copyProperties(ordersCancelDTO,orders);
        orderMapper.update(orders);
    }

    @Override
    public void deliverOrderById(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public void completeOrderById(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }


}
